package com.hns.can.service.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.aop.orgTree.DriverInterfaceAnnotation;
import com.hns.can.common.aop.orgTree.LeftOrgAnnotation;
import com.hns.can.common.constants.GlobalConst;
import com.hns.can.common.entity.BaseEntity;
import com.hns.can.common.formula.FillCodeDscValue;
import com.hns.can.common.formula.FillParamsVo;
import com.hns.can.common.vo.CommonParamsVo;
import com.hns.can.master.entity.BaseCarInfoEntity;
import com.hns.can.master.entity.BaseDrvInfoEntity;
import com.hns.can.master.entity.BaseLineInfoEntity;
import com.hns.can.service.entity.BaseDriverExamInfoEntity;
import com.hns.can.service.entity.BaseDriverExamUploadErrEntity;
import com.hns.can.service.enumrate.BackUpdateDrvTable;
import com.hns.can.service.enumrate.ParseZhenBaoDrvAttExecl;
import com.hns.can.service.vo.DrvAttendanceVo;

import com.hns.tool.pub.SearchConditionVo;
import com.hns.tool.pub.UtilString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.frame.mybatis.Pagination;
import com.hns.frame.service.CommonService;
import com.hns.tool.pub.DateTool;
import com.hns.tool.pub.PubUtil;

/**
 * @版权：HNS 版权所有 (c) 2013
 * @author:JeffXu
 * @version Revision 1.0.0
 * @email:835264047@qq.com
 * @see:
 * @创建日期：2014-8-6
 * @功能说明：驾驶员考勤业务类
 * @begin
 * @修改记录:
 * @修改后版本          修改人      	修改内容
 * @2014-8-6  	         JeffXu        	创建
 * @end
 */
@Service
public class BaseDriverExamInfoService extends CommonService {
    
    @Autowired
    private FillCodeDscValue codeDscValue;

	
    /**
     * @param conditionVo
     * @return
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-6
     * @功能说明：获取驾驶员考勤列表 page对象
     */
    @LeftOrgAnnotation()
    @Transactional
    public Pagination searchDriverExamInfoPage(CommonParamsVo commonParamsVo) throws Exception {
	    Pagination page = this.myBatisPage("baseDriverExamInfo.getBaseDriverExamInfoCnt","baseDriverExamInfo.getBaseDriverExamInfoList",
	    		commonParamsVo,DrvAttendanceVo.class);
        Map<String,String> map = new HashMap<String,String>();
        map.put("lineName", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo1 = new FillParamsVo("lineId", map);
        Map<String,String> map2 = new HashMap<String,String>();
        map2.put("carName", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo2 = new FillParamsVo("carId", map2);
        Map<String,String> map3 = new HashMap<String,String>();
        map3.put("drvName", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo3 = new FillParamsVo("drvId", map3);
        codeDscValue.fillInfoValue(page.getData(), new String[] {GlobalConst.CACHE_KEY_BASE_LINE_INFO, GlobalConst.CACHE_KEY_BASE_CAR_INFO, GlobalConst.CACHE_KEY_BASE_DRV_INFO},vo1, vo2,vo3);
	    return page;
    }
    
    /**
     * @param conditionVo
     * @return
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-6
     * @功能说明：得到驾驶员考勤 list对象
     */
    @SuppressWarnings("unchecked")
    @LeftOrgAnnotation()
    @Transactional
    public List<BaseDriverExamInfoEntity> getBaseDriverExamInfoList(CommonParamsVo commonParamsVo) throws Exception {
        List<BaseDriverExamInfoEntity> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList(
                    "baseDriverExamInfo.getBaseDriverExamInfoList",commonParamsVo), DrvAttendanceVo.class);
        Map<String,String> map = new HashMap<String,String>();
        map.put("lineName", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo1 = new FillParamsVo("lineId", map);
        Map<String,String> map2 = new HashMap<String,String>();
        map2.put("carName", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo2 = new FillParamsVo("carId", map2);
        Map<String,String> map3 = new HashMap<String,String>();
        map3.put("drvName", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo3 = new FillParamsVo("drvId", map3);
        codeDscValue.fillInfoValue(list, new String[] {GlobalConst.CACHE_KEY_BASE_LINE_INFO, GlobalConst.CACHE_KEY_BASE_CAR_INFO, GlobalConst.CACHE_KEY_BASE_DRV_INFO},vo1, vo2,vo3);
        return list;
    }
    
    /**
     * @param attendId
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-7-2
     * @功能说明：删除驾驶员考勤记录
     */
    @Transactional
    public void delDriverExamInfo(String attendId){
        BaseDriverExamInfoEntity entity = commonEntityDao.find(attendId, BaseDriverExamInfoEntity.class);
        commonEntityDao.delete(entity);
    }
    
    /**
     * @param lineId
     * @return
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-7-3
     * @功能说明：通过线路id获得线路信息
     */
    @Transactional
    public BaseLineInfoEntity getLineInfoByLineId(String lineId){
        BaseLineInfoEntity entity = commonEntityDao.find(lineId, BaseLineInfoEntity.class);
        return entity;
    }
    
    /**
     * @param lineId
     * @param carIds
     * @param drvIds
     * @param signInTimes
     * @param signOutTimes
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-7-4
     * @功能说明：批量新增驾驶员考勤信息
     */
    @Transactional
    public void addDrvExam(String lineId, String[] carIds, String[] drvIds,
                String[] signInTimes, String[] signOutTimes) throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        BaseLineInfoEntity lineEntity = this.commonEntityDao.find(lineId, BaseLineInfoEntity.class);
//        String corpId = user.getCorpId();
        String corpId = lineEntity.getCorpId();
        String crtUser = user.getAcctName();
        Date crtTime = new Date();
        
        List<BaseDriverExamInfoEntity> list = new ArrayList<BaseDriverExamInfoEntity>();
        for(int i = 0; i < carIds.length; i++){
            BaseDriverExamInfoEntity entity = new BaseDriverExamInfoEntity();
            /*String attendId = DataUtil.sequenceID();
            entity.setAttendId(attendId);*/
            entity.setAttendId(UtilString.getUUID());
            entity.setCorpId(corpId);
            entity.setLineId(lineId);
            entity.setCarId(carIds[i]);
            entity.setDrvId(drvIds[i]);
            entity.setSignInTime(signInTimes[i]);
            entity.setSignOutTime(signOutTimes[i]);
            try {
                String workDura = new BigDecimal(DateTool.calculateTimeForTimeUnit(signInTimes[i],signOutTimes[i],
                    DateTool.TIME_UNIT_SECONDS) * 1000).toString();
                entity.setWorkDura(workDura);  // 数据库中存成毫秒
            } catch (ParseException e) {
                e.printStackTrace();
            }
            entity.setCrtTime(crtTime);
            entity.setCrtUser(crtUser);
            list.add(entity);
        }
        // 校验考勤时间重叠(list校验)
        if(this.checkDrvExamTimeIncludedList(list)){
            throw new BusinessException(MsgType.WARN.getFlag(), "您输入的考勤时间已经存在！");
        }
        for(BaseDriverExamInfoEntity entity : list){
            // 校验考勤时间重叠(数据库校验)
            if(this.checkDrvExamTimeIncludedDB(entity)){
                throw new BusinessException(MsgType.WARN.getFlag(), "您输入的考勤时间已经存在！");
            }
            commonEntityDao.save(entity);
        }
    }

    /**
     * @param request
     * @param uptAttendId
     * @param uptSignInTime
     * @param uptSignOutTime
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-7-4
     * @功能说明：修改驾驶员考勤信息
     */
    @Transactional
    public void uptDrvExam(HttpServletRequest request, String uptAttendId, String uptSignInTime, String uptSignOutTime) {
        BaseDriverExamInfoEntity entity = commonEntityDao.find(uptAttendId, BaseDriverExamInfoEntity.class);
        
        // 考勤时间重叠校验(只做数据库校验)
        if((!entity.getSignInTime().equals(uptSignInTime) || !entity.getSignOutTime().equals(uptSignOutTime))){ // 有发生时间更改
            entity.setSignInTime(uptSignInTime);
            entity.setSignOutTime(uptSignOutTime);
            if(this.checkDrvExamTimeIncludedDB(entity)){ // 考勤时间重叠 true
                throw new BusinessException(MsgType.WARN.getFlag(), "您输入的考勤时间已经存在！");
            }
        }
        
        try {
            String uptWorkDura = new BigDecimal(DateTool.calculateTimeForTimeUnit(uptSignInTime,uptSignOutTime,
                DateTool.TIME_UNIT_SECONDS) * 1000).toString();
            entity.setWorkDura(uptWorkDura);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        
        entity.setUpdateTime(new Date());
        SysUserEntity user = (SysUserEntity) request.getSession().getAttribute("SES_CURRENTUSER");
        entity.setUpdateUser(user.getAcctName());
        commonEntityDao.update(entity);
    }
    
    /**
     * @return
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     * @创建日期:2014-7-8
     * @功能说明：定时更新所有有关的drvId
     */
    @Transactional
    public int updateDrvIdTimer() {
        int count = 0;
        for(BackUpdateDrvTable e : BackUpdateDrvTable.values()){
            Map<String, String> parameter = new HashMap<String, String>();
            parameter.put("tableName", e.getFlag());
            count =count + this.sqlMapDao.update("drvierInterface.updateDriIdByExam",parameter);
        }
        return count;
    }
    
    /**
     * @param timecardCardno
     * @return
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-18
     * @功能说明：通过考勤卡号获得驾驶员信息
     */
    @Transactional
    public BaseDrvInfoEntity getDrvByTimecardCardno(String corpId, String timecardCardno){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("corpId", corpId);
        params.put("enabledSt", "1");
        params.put("timecardCardno", timecardCardno);
        List<BaseDrvInfoEntity> list = commonEntityDao.findByParamsIgnoreNullValue(BaseDrvInfoEntity.class, params);
        if(list.size() > 0){
            return list.get(0);
        }
        return null;
    }
    
    /**
     * @param lineName
     * @return
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-18
     * @功能说明：通过线路名称获得线路信息
     */
    @Transactional
    public BaseLineInfoEntity getLineIdByLineName(String corpId, String lineName){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("corpId", corpId);
        params.put("enabledSt", "1");
        params.put("lineName", lineName);
        List<BaseLineInfoEntity> list = commonEntityDao.findByParamsIgnoreNullValue(BaseLineInfoEntity.class, params);
        if(list.size() > 0){
            return list.get(0);
        }
        return null;
    }
    
    /**
     * @param licPltNo
     * @return
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-18
     * @功能说明：通过车牌获得车辆信息
     */
    @Transactional
    public BaseCarInfoEntity getCarIdByLicPltNo(String corpId, String licPltNo){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("corpId", corpId);
        params.put("enabledSt", "1");
        params.put("licPltNo", licPltNo);
        List<BaseCarInfoEntity> list = commonEntityDao.findByParamsIgnoreNullValue(BaseCarInfoEntity.class, params);
        if(list.size() > 0){
            return list.get(0);
        }
        return null;
    }
    
    /**
     * @return
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-18
     * @功能说明：获取驾驶员考勤上传错误信息表的list对象
     */
    @SuppressWarnings("unchecked")
    @Transactional
    public List<BaseEntity> searchDriverExamUploadErrList(String licPltNo,String corpId, String qImportDate, String qErrorType) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("qImportDate", qImportDate);
        params.put("qErrorType", qErrorType);
        params.put("qcorpId", corpId);
        params.put("licPltNo", licPltNo);
        List<BaseEntity> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList(
                    "baseDriverExamInfo.getBaseDriverExamUploadErrList", params), BaseDriverExamUploadErrEntity.class);
        
        Map<String,String> mapTmp = new HashMap<String,String>();
        mapTmp.put("errorType", "ERT00000");
        mapTmp.put("errorHint", "ERH00000");
        codeDscValue.fillCodeDscValue(list, mapTmp);
        
        return list;
    }
    
    /**
     * @param errorId
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-19
     * @功能说明：删除考勤上传错误信息
     */
    @Transactional
    public void delErrInfo(String errorId){
        BaseDriverExamUploadErrEntity entity = commonEntityDao.find(errorId, BaseDriverExamUploadErrEntity.class);
        commonEntityDao.delete(entity);
    }
    
    /**
     * @param errorIds
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2015-1-8
     * @功能说明：批量删除考勤上传错误信息
     */
    @Transactional
    public void delErrInfos(String[] errorIds) {
        for(String errorId : errorIds){
            BaseDriverExamUploadErrEntity entity = commonEntityDao.find(errorId, BaseDriverExamUploadErrEntity.class);
            commonEntityDao.delete(entity);
        }
    }
    
    /**
     * @param uptErrorIds
     * @param uptOprtLines
     * @param uptLicPltNos
     * @param uptDrvNames
     * @param uptTimecardCardnos
     * @param uptSignInTimes
     * @param uptSignOutTimes
     * @throws Exception
     * @author:JeffXu
     * @return 
     * @email:835264047@qq.com
     * @创建日期:2014-8-27
     * @功能说明：重新导入修改后的驾驶员考勤信息
     */
    @Transactional
    public List<BaseDriverExamUploadErrEntity> packToList(String corpId, String[] uptErrorIds, 
                    String[] uptOprtLines, String[] uptLicPltNos, String[] uptDrvNames, String[] uptTimecardCardnos, 
                    String[] uptSignInTimes, String[] uptSignOutTimes) throws Exception {
        // 组装成list对象
        List<BaseDriverExamUploadErrEntity> list = new ArrayList<BaseDriverExamUploadErrEntity>();
        BaseDriverExamUploadErrEntity entity = null;
        for (int i = 0; i < uptErrorIds.length; i++) {
            entity = new BaseDriverExamUploadErrEntity();
            entity.setErrorId(uptErrorIds[i]);
            entity.setOprtLine(uptOprtLines[i]);
            entity.setLicPltNo(uptLicPltNos[i]);
            entity.setDrvName(uptDrvNames[i]);
            entity.setTimecardCardno(uptTimecardCardnos[i]);
            entity.setSignInTime(uptSignInTimes[i]);
            entity.setSignOutTime(uptSignOutTimes[i]);
            entity.setCorpId(corpId);
            list.add(entity);
        }
        return list;
    }
    
    /**
     * @param entity
     * @return
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-27
     * @功能说明：校验考勤时间是否重叠(数据库)
     */
    @Transactional
    public boolean checkDrvExamTimeIncludedDB(BaseEntity entity) {
        Integer cnt = (Integer) sqlMapDao.selectOne("baseDriverExamInfo.checkDrvExamTimeIncludedDB", entity);
        if(cnt > 0){
            return true; // 考勤时间重叠
        }
        return false;
    }
    
    /**
     * @param list
     * @return
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-27
     * @功能说明：校验考勤时间是否重叠(list)
     */
    public boolean checkDrvExamTimeIncludedList(List<BaseDriverExamInfoEntity> list) throws Exception{
        for(int i = 0; i < list.size(); i++){
            for(int j = 0; j < list.size(); j++){
                if(i != j){
                    BaseDriverExamInfoEntity entity = list.get(i);
                    BaseDriverExamInfoEntity tmpEntity = list.get(j);
                    if (entity.getCarId().equals(tmpEntity.getCarId()) 
                                && ((DateTool.compareDate(entity.getSignInTime(), tmpEntity.getSignInTime()) 
                                    && !DateTool.compareDate(entity.getSignInTime(), tmpEntity.getSignOutTime())) 
                                || (DateTool.compareDate(entity.getSignOutTime(), tmpEntity.getSignInTime()) 
                                    && !DateTool.compareDate(entity.getSignOutTime(), tmpEntity.getSignOutTime())))) {
                        return true; // 考勤时间重叠
                    }
                }
            }
        }
        return false;
    }
    
    /**
     * @param attendIds
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-10-16
     * @功能说明：批量删除驾驶员考勤记录
     */
    @Transactional
    public void delDriverExamInfoByAttendIds(List<String> attendIds) {
        for(String attendId : attendIds){
            BaseDriverExamInfoEntity entity = commonEntityDao.find(attendId, BaseDriverExamInfoEntity.class);
            commonEntityDao.delete(entity);
        }
    }
    
    /**
     * @param list
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-15
     * @功能说明：将正常的数据存入[驾驶员考勤信息]，将数据有误的存入[驾驶员考勤上传错误信息]，区别文件上传和重新上传的操作
     */
    @Transactional
    public void saveToDB(String corpId, List<BaseDriverExamUploadErrEntity> list) throws Exception {
        boolean isFirRecord = true;
        String beginTime = "";
        String endTime = "";
        SysUserEntity user = this.getCurrentUser().getUser();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String importDate = sdf1.format(new Date());
        String importTime = sdf2.format(new Date());
        for (BaseDriverExamUploadErrEntity entity : list) {
            if ("ERT00006".equals(entity.getErrorType())) { // 数据正常
                // 获取导入考勤的时间范围(min,max考勤时间)
                String signInTime = entity.getSignInTime();
                String signOutTime = entity.getSignOutTime();
                if(!isFirRecord){
                    if(DateTool.compareDate(beginTime, signInTime)){
                        beginTime = signInTime;
                    }
                    if(DateTool.compareDate(signOutTime, endTime)){
                        endTime = signOutTime;
                    }
                }
                if(isFirRecord){
                    beginTime = signInTime;
                    endTime = signOutTime;
                    isFirRecord = false;
                }
                // 重新上传的数据，对应删除上传错误表中的信息
                if(PubUtil.isNotEmpty(entity.getErrorId())){
                    BaseDriverExamUploadErrEntity tmpEntity = commonEntityDao.find(entity.getErrorId(), BaseDriverExamUploadErrEntity.class);
                    commonEntityDao.delete(tmpEntity);
//                    commonEntityDao.delete(BaseDriverExamUploadErrEntity.class, new String[]{entity.getErrorId()});
                }
                // 存入考勤表中
                BaseDriverExamInfoEntity drvExam = new BaseDriverExamInfoEntity();
                String crtUser = user.getAcctName();
                Date crtTime = new Date();
                drvExam.setAttendId(UtilString.getUUID());
                drvExam.setCorpId(corpId);
                drvExam.setLineId(entity.getLineId());
                drvExam.setCarId(entity.getCarId());
                drvExam.setDrvId(entity.getDrvId());
                drvExam.setSignInTime(entity.getSignInTime());
                drvExam.setSignOutTime(entity.getSignOutTime());
                try {
                    String workDura = new BigDecimal(DateTool.calculateTimeForTimeUnit(entity.getSignInTime(), entity.getSignOutTime(), DateTool.TIME_UNIT_SECONDS) * 1000).toString();
                    drvExam.setWorkDura(workDura); // 数据库中存成毫秒
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                drvExam.setCrtTime(crtTime);
                drvExam.setCrtUser(crtUser);
                Map<String,Object> params = new HashMap<String,Object>();
                params.put("signInTime",drvExam.getSignInTime());
                params.put("signOutTime",drvExam.getSignOutTime() );
                params.put("drvId", drvExam.getDrvId());
                List<BaseDriverExamInfoEntity> check = this.commonEntityDao.findByParamsIgnoreNullValue(BaseDriverExamInfoEntity.class,params);
                if(check.size() > 0){
                	continue;
                }
                commonEntityDao.save(drvExam);
            } else { // 数据有误
                if(PubUtil.isNotEmpty(entity.getErrorId())){ // 重新上传的数据，对应更新上传错误表中的信息
                    BaseDriverExamUploadErrEntity tmpEntity = commonEntityDao.find(entity.getErrorId(), BaseDriverExamUploadErrEntity.class);
                    String[] excludsArray = {"errorId","importDate","importTime","importUser"};
                    PubUtil.copyPropertiesExclude(entity, tmpEntity, excludsArray);
                    tmpEntity.setCorpId(corpId);
                    commonEntityDao.update(tmpEntity);
                }else{
                    entity.setImportDate(importDate);
                    entity.setImportTime(importTime);
                    entity.setImportUser(user.getId());
                    entity.setCorpId(corpId);
                    Map<String,Object> params = new HashMap<String,Object>();
                	params.put("signInTime",entity.getSignInTime());
                    params.put("signOutTime",entity.getSignOutTime() );
                    params.put("oprtLine", entity.getOprtLine());
                    params.put("drvName", entity.getDrvName());
                    params.put("licPltNo", entity.getLicPltNo());
                    params.put("timecardCardno", entity.getTimecardCardno());
                    params.put("corpId", corpId);
                    List<BaseDriverExamUploadErrEntity> check = this.commonEntityDao.findByParamsIgnoreNullValue(BaseDriverExamUploadErrEntity.class,params);
                    if(check.size() > 0){
                    	BaseDriverExamUploadErrEntity dbEntity = check.get(0);
                    	entity.setErrorId(dbEntity.getErrorId());
                    	commonEntityDao.update(entity);
                    }else{
                    	entity.setErrorId(UtilString.getUUID());
                    	commonEntityDao.save(entity);
                    }
                }
            }
        }
        
//        if(PubUtil.isEmpty(beginTime) || PubUtil.isEmpty(endTime)){
//            return null;
//        }
//        SearchConditionVo conditionVo = new SearchConditionVo();
//        conditionVo.setBeginTime(beginTime);
//        conditionVo.setEndTime(endTime);
//        conditionVo.setCorpId(user.getCorpId());
        //modifiy by qianjy 导入考勤时,批量更新驾驶员信息
//        List<String> driverRelTableList=new ArrayList<String>();
//        driverRelTableList.add("T_COMM_ENER_CONS_STAT_INFO");
//        driverRelTableList.add("T_COMM_MFT_ALM");
//        driverRelTableList.add("T_COMM_DRV_SCT_BHV_INFO");
//        conditionVo.setDriverRelTableListName(driverRelTableList);
//        return conditionVo;
    }
    
    /**
     * @param conditionVo
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2015-1-14
     * @功能说明：自动去更新能耗表的驾驶员Id信息
     */
    @DriverInterfaceAnnotation()
    public void uptEnerConsStatInfoDrvId(SearchConditionVo conditionVo) throws Exception {
    	List<String> tableList = conditionVo.getDriverRelTableListName();
		if(PubUtil.isEmpty(tableList))
			return;
		
		Map<String, String> parameter = new HashMap<String, String>();
		parameter.put("corpId", conditionVo.getCorpId());
		parameter.put("beginTime", conditionVo.getBeginTime());
		parameter.put("endTime", conditionVo.getEndTime());
		for (String tableName : tableList) {
			parameter.put("tableName", tableName);
//			sqlMapDao.update("drvierInterface.updateDriIdByExam", parameter);
		}
    }
    
    /**
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2015-1-19
     * @功能说明：调用存储过程“PC_BS_TMP_ENE_DET”重新生成“T_BS_TMP_ENE_DET”数据
     */
    @Transactional
    public void buildEnerConsDetailMidTab(Map<String, Object> paraMap) throws Exception {
        this.sqlMapDao.update("baseDriverExamInfo.buildEnerConsDetailMidTab", paraMap);
    }
    
    /**
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2015-1-19
     * @功能说明：调用存储过程“PC_BS_DAY_ENE_DRV”重新生成“T_BS_DAY_ENE_DRV”数据
     */
    @Transactional
    public void buildEnerConsStatDrvMidTab(Map<String, Object> paraMap) throws Exception {
        this.sqlMapDao.update("baseDriverExamInfo.buildEnerConsStatDrvMidTab", paraMap);
    }
    
    /**
     * 上传珍宝驾驶员考勤信息
     * @param list
     * @param corpId
     * @param user
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor=Exception.class)
    public int saveToDB(List<BaseDriverExamInfoEntity> list,String corpId,SysUserEntity user) throws Exception{
    	int count = 0;
    	Map<String,String> map = ParseZhenBaoDrvAttExecl.getMap();
    	SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
    	SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	for(int i = 2;i<list.size();i++){
    		String signInTimeLate = null;
    		String signOutTimeLate =null;
    		String drvId = null;
    		String lineId = null;
    		BaseDriverExamInfoEntity entity = list.get(i);
    		//判断车有没有在平台注册
    		String licPltNo = entity.getCarId().replace(".", "");
    		Map<String,String> mapId = new HashMap<String,String>();
    		mapId.put("licPltNo", licPltNo);
    		Map<String, String> result = (Map<String, String>) sqlMapDao.selectOne("baseDriverExamInfo.searchByNo", mapId);
    		if(PubUtil.isEmpty(result)){
    			continue;
    		};
    		//签到时间
    		//取出日期
    		String time = entity.getSignInTime();
    		if(time == null){
    			continue;
    		}
    		String num = map.get(entity.getWorkDura());
    		String signInTime = sdf2.format(getSignTime(num,time));
    		entity.setSignInTime(signInTime);
    		String primarykey1 = sdf1.format(getSignTime(num,time));
    		//签退时间
    		time = entity.getSignOutTime();
    		if(time == null){
    			continue;
    		}
    		String signOutTime = sdf2.format(getSignTime(num,time));
    		entity.setSignOutTime(signOutTime);
    		//车辆ID
    		String carId = result.get("CAR_ID");
    		entity.setCarId(carId);
    		//驾驶员ID
    		String workEmpeEmpno = entity.getDrvId();
    		mapId.put("workEmpeEmpno", workEmpeEmpno);
    		Map<String, String> result1 = (Map<String, String>) sqlMapDao.selectOne("baseDriverExamInfo.getDrvId", mapId);
    		if(!PubUtil.isEmpty(result1)){
    			drvId = result1.get("DRV_ID");
    			entity.setDrvId(drvId);
    		};
    		//线路ID
    		mapId.put("carId", carId);
    		Map<String, String> result2 = (Map<String, String>) sqlMapDao.selectOne("baseDriverExamInfo.getLineId", mapId);
    		if(!PubUtil.isEmpty(result2)){
    			lineId = result2.get("LINE_ID");
    			entity.setLineId(lineId);
    		};
    		//企业Id
    		entity.setCorpId(corpId);
    		//生成主键
    		licPltNo = licPltNo.replace("粤", "");
    		String primarykey = getPrimarykey(primarykey1+workEmpeEmpno+licPltNo);
			////取出临时存的班别 
			String class1 = entity.getCrtUser();
			//相差时间
			long inTime = sdf2.parse(signInTime).getTime();
			long outTime = sdf2.parse(signOutTime).getTime();
			saveEntity(entity,primarykey,user,(Math.abs(outTime-inTime))+"");
			if("早晚班".equals(class1)){
				//取出晚班签到,签退时间，拼上日期
				BaseDriverExamInfoEntity entity1 = new BaseDriverExamInfoEntity();
				signInTimeLate = sdf2.format(getSignTime(num,entity.getIconSkin()));
				signOutTimeLate = sdf2.format(getSignTime(num,entity.getRcrdTime()));;
				inTime = sdf2.parse(signInTimeLate).getTime();
				outTime = sdf2.parse(signOutTimeLate).getTime();
				entity1.setSignInTime(signInTimeLate);
				entity1.setSignOutTime(signOutTimeLate);
				entity1.setCarId(carId);
				entity1.setLineId(lineId);
				entity1.setCorpId(corpId);
				entity1.setDrvId(drvId);
				primarykey1 = sdf1.format(getSignTime(num,entity.getIconSkin()));
				primarykey = getPrimarykey(primarykey1+workEmpeEmpno+licPltNo);
				saveEntity(entity1,primarykey,user,(Math.abs(outTime-inTime))+"");
				count++;
			}
			if(count % 300 == 0){
				this.commonEntityDao.clear();
				this.commonEntityDao.flush();
			}
			count++;
    	}	
    	return count;
	}
	//转换时间
	public static Date getSignTime(String num,String time) throws Exception{
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
    	String SignTime = num + " "+ time;
		Date date = sdf1.parse(SignTime);
		return date;
	}
	//不满32位后面自动补0
    public String getPrimarykey(String rcrdId){
    	int n = 32;
    	rcrdId = rcrdId+String.format("%1$0"+(n-rcrdId.length())+"d",0);
    	return rcrdId;
    }
    
    //存到数据苦中
    @Transactional
    public void saveEntity(BaseDriverExamInfoEntity entity,String primarykey,SysUserEntity user,String workDura){
    	BaseDriverExamInfoEntity check = commonEntityDao.find(primarykey,BaseDriverExamInfoEntity.class);
    	entity.setAttendId(primarykey);
    	entity.setWorkDura(workDura);
    	if(PubUtil.isEmpty(check)){
			//创建时间
    		entity.setCrtTime(new Date());
    		//创建人
    		entity.setCrtUser(user.getAcctName());
			this.commonEntityDao.save(entity);
		}
	}
    
    
}
